package service;

import static constant.Constant.SEPARATOR;
import static constant.Constant.STR_HELP;
import static constant.Constant.STR_INVALID_ARG_NUM;
import static constant.Constant.STR_INVALID_COMMAND;
import static constant.Constant.STR_SUCCESS;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.StringTokenizer;

public class Service {
	private boolean quit = false;

	private String line;
	private String command;
	private String response;

	private UserManager userManager = UserManager.getInstance();

	public Service(BufferedReader in, DataOutputStream out) throws IOException {
		while (!quit) {
			line = in.readLine();
			System.out.println("New Command : " + line);

			StringTokenizer st = new StringTokenizer(line);
			if (st.hasMoreTokens()) {
				command = st.nextToken();
				if (command.equalsIgnoreCase(new String("LIST"))) {
					response = userManager.toString();
				} else if (command.equalsIgnoreCase(new String("CREATE"))) {
					String surnom = new String();
					String nom = new String();
					if (st.hasMoreTokens()) {
						surnom = st.nextToken();
						if (st.hasMoreTokens()) {
							nom = st.nextToken();
							response = userManager.add(surnom, nom);
						} else {
							response = STR_INVALID_ARG_NUM;
						}
					} else {
						response = STR_INVALID_ARG_NUM;
					}
				} else if (command.equalsIgnoreCase(new String("EDIT"))) {
					String surnom = new String();
					String nom = new String();
					if (st.hasMoreTokens()) {
						surnom = st.nextToken();
						if (st.hasMoreTokens()) {
							nom = st.nextToken();
							response = userManager.add(surnom, nom);
						} else {
							response = STR_INVALID_ARG_NUM;
						}
					} else {
						response = STR_INVALID_ARG_NUM;
					}
				} else if (command.equalsIgnoreCase(new String("DELETE"))) {
					String surnom = new String();
					if (st.hasMoreTokens()) {
						surnom = st.nextToken();
						response = userManager.delete(surnom);
					} else {
						response = STR_INVALID_ARG_NUM;
					}
				}  else if (command.equalsIgnoreCase(new String("SHOW"))) {
					String surnom = new String();
					if (st.hasMoreTokens()) {
						surnom = st.nextToken();
						response = userManager.show(surnom);
					} else {
						response = STR_INVALID_ARG_NUM;
					}
				} else if (command.equalsIgnoreCase(new String("HELP"))) {
					response = STR_HELP;
				} else if (command.equalsIgnoreCase(new String("QUIT"))) {
					quit = true;
					response = STR_SUCCESS;
				} else {
					response = STR_INVALID_COMMAND;
				}
			}
			System.out.println(response);
			out.writeBytes(response + "\n"+SEPARATOR+"\n");
		}
	}
}
